<template>
  <div>
    <a-modal v-model="visible" title="推广" :width="700" :footer="null" destroyOnClose class="spread-modal" forceRender>
      <a-tabs default-active-key="1">
        <a-tab-pane key="1" tab="订阅推广">
          <h4>小程序短链接</h4>
          <p>{{ shortUrl[0] }} <a-button type="primary" :data-clipboard-text="shortUrl[0]" @click="copy('copy-sub')" id="copy-sub">复制</a-button></p>
          <h4>小程序海报</h4>
          <div style="margin-bottom: 12px">
            <a-skeleton :paragraph="false" :active="true" :loading="!imgList[0]">
              <img :src="imgList[0]" alt="" class="thumb-poster" @click="openBigImg(0)" />
              <a-button type="primary" size="small" @click="downloadImg(imgList[0], '订阅推广小程序海报')">下载</a-button>
            </a-skeleton>
          </div>
          <h4>公众号海报</h4>
          <div>
            <a-skeleton :paragraph="false" :active="true" :loading="!imgList[1]">
              <img :src="imgList[1]" alt="" class="thumb-poster" @click="openBigImg(1)" />
              <a-button type="primary" size="small" @click="downloadImg(imgList[1], '订阅推广公众号海报')">下载</a-button>
            </a-skeleton>
          </div>
        </a-tab-pane>
        <a-tab-pane key="2" tab="要盒推广">
          <h4>小程序短链接</h4>
          <p>{{ shortUrl[1] }} <a-button type="primary" :data-clipboard-text="shortUrl[1]" @click="copy('copy-want')" id="copy-want">复制</a-button></p>
          <h4>小程序海报</h4>
          <div style="margin-bottom: 12px">
            <a-skeleton :paragraph="false" :active="true" :loading="!imgList[2]">
              <img :src="imgList[2]" alt="" class="thumb-poster" @click="openBigImg(2)" />
              <a-button type="primary" size="small" @click="downloadImg(imgList[2], '要盒推广小程序海报')">下载</a-button>
            </a-skeleton>
          </div>
          <h4>公众号海报</h4>
          <div>
            <a-skeleton :paragraph="false" :active="true" :loading="!imgList[3]">
              <img :src="imgList[3]" alt="" class="thumb-poster" @click="openBigImg(3)" />
              <a-button type="primary" size="small" @click="downloadImg(imgList[3], '要盒推广公众号海报')">下载</a-button>
            </a-skeleton>
          </div>
        </a-tab-pane>
      </a-tabs>
      <section class="canvas">
        <div ref="imgContent" class="imgContent" v-for="(item, index) in exclusive" :key="index">
          <div class="cover">
            <img :src="item.imgUrl" alt="" />
          </div>
          <div class="info">
            <div class="head">
              <img :src="fashInfo.photo" alt="" />
            </div>
            <div class="fas-name">{{ fashInfo.name }}</div>
            <p class="memo"><span>搭配师说：</span>{{ memo }}</p>
            <div class="ads">
              <img :src="item.codeUrl" alt="" class="code" />
              <div>
                <p>不止盒子，你的专属搭配师<br />扫描二维码查看</p>
                <img src=" https://img.bzhz.jnbygroup.com/jnbyss.png" alt="" class="logo" />
              </div>
            </div>
          </div>
        </div>
      </section>
    </a-modal>
    <BigImg :visibleImgs="visibleImgs" :imgList="bigImgList" :goToIndex="goToIndex" @closeBig="closeBig"></BigImg>
  </div>
</template>
<script>
import { exclusiveData, createSceneSubAndAskBox, currFashioner } from '@/api/box/setting'
import { getHtml2canvas, copyUrl } from '@/views/box/util/global.js'
import BigImg from '../UserMsg/bigImg'
import Clipboard from 'clipboard'
export default {
  components: { BigImg },
  data() {
    return {
      visible: false,
      skeletonLoading: true,
      fashInfo: {},
      memo: '',
      exclusive: [], // 推广
      imgList: [],
      visibleImgs: false,
      bigImgList: [],
      goToIndex: 0,
      shortUrl: []
    }
  },
  mounted() {
    this.fetchExclusiveData()
  },
  methods: {
    show() {
      if (this.exclusive.length > 0) {
        this.visible = true
        this.imgList = []
        this.skeletonLoading = true

        if (sessionStorage.getItem('SpreadImgs')) {
          this.imgList = sessionStorage.getItem('SpreadImgs').split('@')
          console.log(this.imgList)
        } else {
          let self = this
          setTimeout(function () {
            if (self.exclusive.length > 0) {
              self.$nextTick(() => {
                self.loadingImg()
              })
            } else {
              self.$message.warning('暂无推广图片！')
              self.visible = false
            }
          }, 100)
        }
      } else {
        this.$message.warning('暂无推广信息！')
      }
    },
    async loadingImg() {
      this.imgList = []
      for (let index in this.exclusive) {
        console.log(index, new Date())
        let canvasID = this.$refs.imgContent[index]
        let img = await getHtml2canvas(canvasID, 0.9)
        console.log(index + 'img', new Date())
        this.imgList.push(img)
      }
      // console.log(this.imgList)
      sessionStorage.setItem('SpreadImgs', this.imgList.join('@'))
      this.skeletonLoading = false
    },
    createImg() {},
    downloadImg(url, name) {
      const imgUrl = url
      if (window.navigator.msSaveOrOpenBlob) {
        console.log(1)
        // 如果浏览器支持msSaveOrOpenBlob方法（也就是使用IE浏览器的时候），那么调用该方法去下载图片
        var bstr = atob(imgUrl.split(',')[1])
        var n = bstr.length
        var u8arr = new Uint8Array(n)
        while (n--) {
          u8arr[n] = bstr.charCodeAt(n)
        }
        var blob = new Blob([u8arr])
        window.navigator.msSaveOrOpenBlob(blob, name + '.' + 'png')
      } else {
        // 这里就按照chrome等新版浏览器来处理
        const a = document.createElement('a')
        a.href = imgUrl
        a.setAttribute('download', name)
        a.click()
      }
    },
    // 推广信息
    async fetchExclusiveData() {
      await this.fetchFashioner()
      let result = await this.getExclusive()
      if (result && result.length > 0) {
        let list = result
        let wxMaterialIds = []
        for (let item of list) {
          if (item.type == 0) {
            wxMaterialIds[0] = item.wxMaterialId
            if (item.imgType == 0) {
              this.exclusive[0] = { type: 0, wxMaterialId: item.wxMaterialId, imgUrl: item.imgUrl, imgType: 0 }
              if (item.imgUrl) {
                // var subxcxImg = new Image()
                let exist = await this.imageIsExist(item.imgUrl)
                if (exist) {
                  // subxcxImg.setAttribute('src', item.imgUrl)
                }
              }
            }
            if (item.imgType == 1) {
              this.exclusive[1] = { type: 0, wxMaterialId: item.wxMaterialId, imgUrl: item.imgUrl, imgType: 1 }
              await this.imageIsExist(item.imgUrl)
            }
          } else if (item.type == 1) {
            wxMaterialIds[1] = item.wxMaterialId
            if (item.imgType == 0) {
              this.exclusive[2] = { type: 1, wxMaterialId: item.wxMaterialId, imgUrl: item.imgUrl, imgType: 0 }
              await this.imageIsExist(item.imgUrl)
            }
            if (item.imgType == 1) {
              this.exclusive[3] = { type: 1, wxMaterialId: item.wxMaterialId, imgUrl: item.imgUrl, imgType: 1 }
              await this.imageIsExist(item.imgUrl)
            }
          }
        }
        await this.generateCode(wxMaterialIds)
      } else {
        this.exclusive = []
      }
    },
    fetchFashioner() {
      return currFashioner().then(res => {
        if (res.code == 0) {
          this.fashInfo = res.data
          this.memo = res.data.memo.length > 36 ? res.data.memo.slice(0, 36) + '...' : res.data.memo
        } else {
          this.$message.warning(res.msg)
        }
      })
    },
    getExclusive() {
      return exclusiveData().then(res => {
        if (res.code == 0) {
          return res.data
        } else {
          this.$message.warning(res.msg)
          return false
        }
      })
    },
    generateCode(wxMaterialIds) {
      let params = {
        requestData: {
          wxMaterialIds: wxMaterialIds
        }
      }
      return createSceneSubAndAskBox(params).then(res => {
        if (res.code == 0) {
          // codeUrl 小程序 , qrcodeUrl 二维码
          this.exclusive[0].codeUrl = res.data[0].codeUrl
          this.exclusive[1].codeUrl = res.data[0].qrcodeUrl
          this.exclusive[2].codeUrl = res.data[1].codeUrl
          this.exclusive[3].codeUrl = res.data[1].qrcodeUrl
          this.shortUrl[0] = res.data[0].shortUrl
          this.shortUrl[1] = res.data[1].shortUrl
          console.log(this.exclusive)
        } else {
          this.$message.warning(res.msg)
        }
      })
    },
    // 预下载图片
    imageIsExist(url) {
      return new Promise(resolve => {
        var img = new Image()
        img.onload = function () {
          if (this.complete == true) {
            resolve(true)
            img = null
          }
        }
        img.onerror = function () {
          resolve(false)
          img = null
        }
        img.src = url
      })
    },
    openBigImg(index) {
      if (this.imgList.length == 4) {
        this.goToIndex = index
        this.visibleImgs = true
        this.bigImgList = this.imgList
      } else {
        this.$message.warning('正在生成中，请稍后')
      }
    },
    closeBig() {
      this.goToIndex = 0
      this.visibleImgs = false
      this.bigImgList = []
    },
    copy(id) {
      let tag = '#' + id
      var clipboard = new Clipboard(tag)
      clipboard.on('success', e => {
        console.log(e)
        this.$message.success('复制成功')
        // 释放内存
        clipboard.destroy()
      })
      clipboard.on('error', e => {
        console.log(e)
        // 不支持复制
        console.log('复制失败')
        // 释放内存
        clipboard.destroy()
      })
    }
  }
}
</script>
<style lang="less" scoped>
.thumb-poster {
  width: 100px;
  margin-right: 12px;
  cursor: pointer;
}
.spread-modal {
  /deep/.ant-modal-body {
    padding-top: 0;
  }
}
.canvas {
  position: absolute;
  z-index: -2;
  top: 0;
  opacity: 0;
}
.imgContent {
  position: absolute;
  top: 0;
  width: 538px;
  border-radius: 8px;
  overflow: hidden;
  .cover {
    width: 538px;
    height: 580px;
    img {
      width: 100%;
    }
  }
  .info {
    position: relative;
    background: #fff;
    width: 100%;
    padding: 30px;
    box-sizing: border-box;
    .head {
      width: 82px;
      height: 82px;
      position: absolute;
      border-radius: 42px;
      left: 30px;
      top: -41px;
      z-index: 2;
      overflow: hidden;
      img {
        width: 100%;
      }
      // object-fit: cover;
    }
    .fas-name {
      font-family: PingFangSC-Medium, PingFang SC;
      font-weight: 500;
      font-size: 22px;
      color: #333333;
      line-height: 32px;
      position: absolute;
      left: 124px;
      top: 8px;
    }
    .memo {
      margin-top: 26px;
      font-size: 22px;
      color: #333333;
      line-height: 32px;
      margin-bottom: 28px;
      width: 100%;
      display: -webkit-box;
      /*! autoprefixer: off; */
      -webkit-box-orient: vertical;
      -webkit-line-clamp: 2; /* 这里是超出几行省略 */
      overflow: hidden;

      span {
        font-family: PingFangSC-Medium, PingFang SC;
        font-weight: 500;
      }
    }
    .ads {
      display: flex;
      justify-content: space-between;
      p {
        font-size: 18px;
        font-family: PingFangSC-Regular, PingFang SC;
        font-weight: 400;
        color: #666666;
        line-height: 28px;
        margin-bottom: 20px;
        text-align: right;
      }
    }
    .logo {
      width: 78px;
      float: right;
    }
    .code {
      width: 96px;
      height: 96px;
    }
  }
}
</style>

